package igz.fleaxy.air {

	import flash.events.Event;
	import flash.events.ProgressEvent;
	import flash.filesystem.File;
	import flash.filesystem.FileMode;
	import flash.filesystem.FileStream;
	import flash.net.URLRequest;
	import flash.net.URLStream;
	import flash.utils.ByteArray;
		
	/**
	 * @author Intelygenz | www.intelygenz.com
	 */
	public class DownloadManager {
		
		private var _Request    : URLRequest; 
		private var _Stream     : URLStream;
		private var _FileStream : FileStream;
		
		public function DownloadManager() {
			_Stream = new URLStream();
			_FileStream = FileStream();
			
			super();
		}
		
		/**
		 * Method to download a file from a server. 
		 * 
		 * @param fileURL the server URL
		 * @param fileLocalLocation the location to be saved
		 * 
		 */		
		public function $DownloadFileFromServer( p_fileURL : String, p_fileLocalPath : String ):void {
			
			var file:File = File.desktopDirectory.resolvePath(p_fileLocalPath);
			request = new URLRequest(p_fileURL);
	        fileStream.openAsync(file, FileMode.WRITE);
	        
	        stream.addEventListener(ProgressEvent.PROGRESS, _OnDownloadProgress);
	        stream.addEventListener(Event.COMPLETE, _OnDownloadComplete);
			
	        stream.load(request);
		}
		
		/**
         * Event handler to handle the async progress events.
         * 
         * @param event
         * 
         */		
        private function _OnDownloadProgress(event:ProgressEvent) : void {
            
			var byteArray:ByteArray = new ByteArray();
            var value:Number = event.bytesLoaded;
            var total:Number = event.bytesTotal;
            var precent:Number = Math.round(value*100/total);
            
            stream.readBytes(byteArray, 0, stream.bytesAvailable);
            fileStream.writeBytes(byteArray, 0, byteArray.length);
			
			var progressEvent:ProgressEvent = new ProgressEvent(ProgressEvent.PROGRESS);
			progressEvent.bytesLoaded = value;
			progressEvent.bytesTotal = total;
			
			this.dispatchEvent(progressEvent);
    	}
    	
    	/**
    	 * Event handler to handle the event complete.
    	 * 
    	 * @param event
    	 * 
    	 */    	
    	private function _OnDownloadComplete(event:Event) : void {
            
			fileStream.close();
            stream.close(); 
            
            stream.removeEventListener( ProgressEvent.PROGRESS, _OnDownloadProgress );
            stream.removeEventListener( Event.COMPLETE, _OnDownloadComplete );
            
			var completeEvent:Event = new Event(Event.COMPLETE);
			this.dispatchEvent(completeEvent);    
    	}		
		
	}

}